from apps.account.baseViews import *
from apps.common.wx.wxapi import getOpenid
from apps.system.lessee.dao import LesseeDao
from apps.common.utils.tools import random_str, random_uuid
from apps.chat.message.functions import MessageFun

class AccountViewSet(BaseAccountViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = AccountDao().findAll()
        return _list

    '''获取用户信息'''
    @action(methods=['post'], detail=False)
    def getAccountInfo(self, request):
        params = getRequestParams(self.request)
        # 更新最近登录时间
        AccountDao().update(self.request.user.id, {"last_login": datetime.datetime.now()})
        obj = AccountDao().findOneByObjId(self.request.user.id)
        model = AccountModelSerializer(obj).data
        return Response(response_success(model))
    
    '''快捷登录'''
    @action(methods=['post'], detail=False, authentication_classes=[], permission_classes=[])
    def wxLoginForOpenid(self, request):
        params = getRequestParams(self.request)
        _code = params.get('code')
        _clientname = params.get('clientname')
        _parentCode = params.get('parentCode')
        if isEmptyStr(_code):
            return Response(response_message('code参数不能为空'))
        if isEmptyStr(_clientname):
            return Response(response_message('clientname参数不能为空'))
        session_data = getOpenid(params.get("code"), _clientname)
        print('session_data', session_data)
        _users = AccountDao().findAllByLesseeId(params.get('lessee')).filter(openid=session_data.get('openid'))
        # print('_users', _users)
        if _users.exists():  # 老用户登录
            _user = _users.first()
            _token = AccountDao().replaceToken(_user.id)
            return Response(response_success({'token': _token.key, 'openid': _user.openid}))
        else:  # 新用户，去注册
            _lessee = LesseeDao().findOneByObjId(params.get('lessee'))
            if _lessee.isInviteReg and not _parentCode:
                return Response(response_action(10002, '请先通过邀请码注册'))

            data = {}
            data['lessee'] = params.get('lessee')
            data['role'] = 'custom'
            data['username'] = random_uuid()
            data['openid'] = session_data.get('openid')

            if _parentCode:
                _parent = AccountDao().findOneByFilters({'code': _parentCode})
                if not _parent:
                    return Response(response_message('上级不存在'))
                data['parent'] = _parent.id

            _user = AccountDao().create(data)
            print('_user', _user)
            if _user:
                code = 100000 + _user.id
                AccountDao().update(_user.id, { "code": code, "username": code })
            _token = AccountDao().replaceToken(_user.id)
            MessageFun().sendMessage(None, AccountDao().findOneByObjId(_user.id), 'system', {'title': '系统通知', 'content': '欢迎注册！'})
        return Response(response_success({'token': _token.key, 'openid': _user.openid}))
    
    '''退出登录'''
    @action(methods=['post'], detail=False,authentication_classes=[],permission_classes=[])
    def logout(self, request):
        params = getRequestParams(request)
        if not params.get("token"):
            return Response(response_success("操作成功"))
        _tokens = Token.objects.filter(key = params.get("token"))
        if not _tokens.exists():
            return Response(response_success("操作成功"))
        _toke = _tokens.first()
        _user = _toke.user
        # if not _user.password:
        #     return Response(response_action(1001, '您还未设置登录密码，请设置登录密码之后再退出登录！'))
        _tokens.delete()
        return Response(response_success("操作成功"))